//
//  BKLHealth_MCController.m
//  BKLMedicalCare
//
//  Created by ma c on 2017/6/14.
//  Copyright © 2017年 q mac. All rights reserved.
//

#import "BKLHealth_MCController.h"
#import "BKLHealth_MCFamousDoctorController.h"
#import "BKLHealth_MCDiseaseController.h"
#import "BKLHealth_MCView.h"

#pragma mark - page view controller
#pragma mark -
@interface BKLHealth_MCPageViewController : UIPageViewController <UIPageViewControllerDelegate, UIScrollViewDelegate>
@property (nonatomic, assign)NSInteger currentPage;
@property (nonatomic, copy) void(^scrollDidScroll)(CGFloat x);
@property (nonatomic, strong) NSArray *readyViewControllers;
@property (nonatomic, assign) CGFloat estimateOffsetX;
@end
@implementation BKLHealth_MCPageViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    for (UIView *subview in self.view.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            UIScrollView *scrollView = (UIScrollView *)subview;
            scrollView.delegate = self;
        }
    }
}

- (void)addListenerWithReadyViewController:(NSArray *)viewControllers scroll:(void(^)(CGFloat x))scrollDidScroll {
    _readyViewControllers = viewControllers;
    _scrollDidScroll = scrollDidScroll;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat pageWidth = self.view.frame.size.width;
    for (UIViewController *vc in _readyViewControllers) {
        
        CGPoint p = [vc.view convertPoint:CGPointZero toView:self.view];
        if (p.x > 0 && p.x < pageWidth) {
            NSInteger estimatePage = [_readyViewControllers indexOfObject:vc];
            _estimateOffsetX = estimatePage *pageWidth - p.x;
        }
    }
    
    //
    if (_estimateOffsetX >= (_readyViewControllers.count - 1) * pageWidth) {
        CGPoint p = [[_readyViewControllers.lastObject view] convertPoint:CGPointZero toView:self.view];
        _estimateOffsetX = (_readyViewControllers.count - 1) * pageWidth -p.x;
    }
    
    if (_scrollDidScroll) {
        _scrollDidScroll(_estimateOffsetX);
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat pageWidth = self.view.frame.size.width;
    _currentPage = round(_estimateOffsetX / pageWidth);
    if (_currentPage < 0) {
        _currentPage = _readyViewControllers.count - 1;
    }
    _estimateOffsetX = _currentPage *pageWidth;
    if (_scrollDidScroll) {
        _scrollDidScroll(_estimateOffsetX);
    }
}
@end

#pragma mark - view controller
#pragma mark -

@interface BKLHealth_MCController ()<UIPageViewControllerDelegate, UIPageViewControllerDataSource, BKLHealth_MCNavigatonViewDelegate>

@property (nonatomic, strong)BKLHealth_MCPageViewController *pageViewController;
@property (nonatomic, strong)NSArray <UIViewController *>*viewControllers;
@property (nonatomic, strong)BKLHealth_MCNavigatonView *navigationView;

@property (nonatomic, assign)NSInteger selectedIndex;
@property (nonatomic, assign)BOOL navigationBarStatus;
@end

@implementation BKLHealth_MCController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _navigationBarStatus = self.navigationController.isNavigationBarHidden;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:_navigationBarStatus animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self initializeComponents];
    
    __weak typeof(self)weakSelf = self;
    [_pageViewController addListenerWithReadyViewController:_viewControllers scroll:^(CGFloat x) {
        [weakSelf.navigationView scrollDidScrll:x];
    }];
}

- (void)initializeComponents {
    
    _viewControllers = [self viewControllers];
    
    _navigationView = [[BKLHealth_MCNavigatonView alloc] init];
    _navigationView.deleagte = self;
    [self.view addSubview:_navigationView];
    
    _pageViewController = ({
        // 间距 10
        NSDictionary *options = @{UIPageViewControllerOptionInterPageSpacingKey : @10};
        BKLHealth_MCPageViewController *pageVC = [[BKLHealth_MCPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:options];
        pageVC.delegate = self;
        pageVC.dataSource = self;
        pageVC.view.frame = CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 64);
        pageVC.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [pageVC setViewControllers:@[_viewControllers.firstObject] direction:UIPageViewControllerNavigationDirectionReverse animated:NO completion:nil];
        pageVC;
    });
    
    [self addChildViewController:_pageViewController];
    [self.view addSubview:_pageViewController.view];

    
}

// 获取子试图控制器请使用 _viewControllers 该方法在viewController生命周期只调用一次
- (NSArray <UIViewController *>*)viewControllers {
    NSMutableArray *array = [NSMutableArray array];
    BKLHealth_MCFamousDoctorController *doctorVC = [[BKLHealth_MCFamousDoctorController alloc] init];
    [array addObject:doctorVC];
    BKLHealth_MCDiseaseController *diseaseVC = [[BKLHealth_MCDiseaseController alloc] init];
    [array addObject:diseaseVC];
    return array.copy;
}

#pragma mark - navigation view delegate
- (void)navigationView:(BKLHealth_MCNavigatonView *)view didSelect:(NSInteger)index {
    UIViewController *viewController = _viewControllers[index];
    UIPageViewControllerNavigationDirection dircetion = index == 0 ? UIPageViewControllerNavigationDirectionReverse : UIPageViewControllerNavigationDirectionForward;
    [_pageViewController setViewControllers:@[viewController] direction:dircetion animated:YES completion:nil];
}


#pragma mark - page view controller delegate

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    
    NSInteger index = [_viewControllers indexOfObject:viewController];
    if (index == 0 || index == NSNotFound) {
        return nil;
    }
    index--;
    return [_viewControllers objectAtIndex:index];
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger index = [_viewControllers indexOfObject:viewController];
    if (index == _viewControllers.count - 1 || index == NSNotFound) {
        return nil;
    }
    index++;
    return [_viewControllers objectAtIndex:index];
}

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    UIViewController *viewController = pendingViewControllers.firstObject;
    NSInteger index = [_viewControllers indexOfObject:viewController];
    _selectedIndex = index;
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        [_navigationView scrollAtIndex:_selectedIndex];
    }
}

@end
